package com.zzyl.nursing.service.impl;

import cn.hutool.core.date.LocalDateTimeUtil;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.nursing.domain.Reservation;
import com.zzyl.nursing.domain.TimeBean;
import com.zzyl.nursing.dto.ReservationDto;
import com.zzyl.nursing.mapper.ReservationMapper;
import com.zzyl.nursing.service.ReservationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class ReservationServiceImpl implements ReservationService {

    private static final int RESERVATION_SATUS = 0;
     private static final int CANCEL_STATUS = 2;
    // 每个时间段的总容量
    private static final int TOTAL_CAPACITY = 6;
    @Autowired
    private ReservationMapper reservationMapper;


    /**
     * 查询当天取消预约数量
     *
     * @return
     */
    @Override
    public Integer cancelledCount() {
        //通过long类型毫秒值获取当天开始时间和结束时间
        long time = System.currentTimeMillis();
        LocalDateTime ldt = LocalDateTimeUtil.of(time);
        LocalDateTime startTime = ldt.toLocalDate().atStartOfDay();
        LocalDateTime endTime = startTime.plusDays(1);
        log.info("开始时间：{}，结束时间：{}", startTime, endTime);
        //获取当前用户ID
        Long userId = UserThreadLocal.getUserId();
        Integer count = reservationMapper.cancelledCount(userId, startTime, endTime);
        if (count > 3) {
            //当天取消预约次数大于3次，则不让预约
            UserThreadLocal.remove();
        }
        return count;
    }

    /**
     * 查询每个时间段剩余预约次数
     *
     * @return
     */
    @Override
    public Integer getCountByTime(Long time) {
        Long userId = UserThreadLocal.getUserId();

        LocalDateTime ldt = LocalDateTimeUtil.of(time);
        LocalDateTime startTime = ldt.toLocalDate().atStartOfDay();
        //开始时间加半个小时
        LocalDateTime endTime = startTime.plusHours(1);
        //reservationMapper.countReservationsByDate(startTime, endTime);
        ArrayList<TimeBean> timeBeans = new ArrayList<>();

        return null;
    }

    /**
     * 查询每个时间段剩余预约次数
     *
     * @param timestamp 时间戳（表示要查询的日期）
     * @return
     */
    @Override
    public List<TimeBean> getRemainingCountsByDate(long timestamp) {
        // 1. 将时间戳转换为日期
        Date date = new Date(timestamp);

        // 2. 计算当天的开始和结束时间
        LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();

        // 设置开始时间 (00:00:00)
        LocalDateTime startTime = localDate.atStartOfDay();

        // 设置结束时间 (23:59:59.999999999)
        LocalDateTime endTime = localDate.atTime(LocalTime.MAX);

        // 3. 查询数据库获取预约数量
        List<TimeBean> reservedCounts = reservationMapper.countReservationsByDate(
                Date.from(startTime.atZone(ZoneId.systemDefault()).toInstant()),
                Date.from(endTime.atZone(ZoneId.systemDefault()).toInstant())
        );

        // 4. 计算剩余次数 = 总容量(6) - 已预约数量
        reservedCounts.forEach(dto -> {
            int remaining = TOTAL_CAPACITY - dto.getCount();
            dto.setCount(Math.max(remaining, 0)); // 确保不小于0
        });

        return reservedCounts;
    }

    /**
     * 新增预约
     */
    @Override
    public void addReservation(ReservationDto dto) {
        Reservation reservation = new Reservation();
        BeanUtils.copyProperties(dto, reservation);

        reservation.setStatus(RESERVATION_SATUS);
        reservation.setCreateTime(LocalDateTime.now());
        Long l = UserThreadLocal.get();
        reservation.setCreateBy(Integer.parseInt(l.toString()));
        reservationMapper.addReservation(reservation);
    }

    /**
     * 分页查询预约列表
     *
     * @param status
     * @return
     */
    @Override
    public List<Reservation> selectReservationList(Integer status) {
        List<Reservation> list = reservationMapper.selectReservationList(status);
        return list;
    }

    /**
     * 取消预约
     */
    @Override
    public void cancelReservation(Long id) {
        Long userId = UserThreadLocal.get();

        reservationMapper.cancelReservation(id, userId,CANCEL_STATUS);
    }
}
